const BASE_URL = 'http://159.75.72.254/';
/**
 * @description http请求封装
 */

export default class Http{
  /**
   * 请求方法初始化
   */
  constructor(){

  }
  request(method, url, data, isLoading = true, header = 'application/json;charset=UTF-8'){
    if (isLoading) {
      wx.showLoading({
        title: '加载中',
        mask: true
      });
    }
    let promise = new Promise((resolve, reject) => {
      wx.request({
        url: `${BASE_URL}${url}`,
        data: data,
        method: method || 'GET',
        header: {
          "Content-Type": header,
        },
        success: res => {
          if(isLoading){
            wx.hideLoading();
          }
          if((res.statusCode + '').indexOf('2') == 0){
            resolve(res.data);
          }else {
            wx.showToast({
              title: '网络异常，请重试',
              icon: 'none'
            });
            reject('网络异常，请重试');
          }
        },
        fail: rej => {
          if(isLoading){
            wx.hideLoading();
          }
          reject(rej);
        }
      })
    });
    return promise;
  }
  /**
   * 上传图片
   * @param {string} imgUrl 
   */
  uploadImg(imgUrl){
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    let promise = new Promise((resolve, reject) => {
      wx.uploadFile({
        filePath: imgUrl,
        name: 'upfile',
        url: `${BASE_URL}Home/UpLoadImgs`,
        header: {
          "Content-Type": "application/json;charset=UTF-8",
        },
        success: res => {
          wx.hideLoading();
          if((res.statusCode + '').indexOf('2') == 0){
            resolve(res.data);
          }else {
            if(url != 'Home/MsgReadAPI'){
              wx.showToast({
                title: '网络异常，请重试',
                icon: 'none'
              });
            }
            reject('网络异常，请重试');
          }
        },
        fail: rej => {
          wx.hideLoading();
          reject(rej);
        }
      })
    });
    return promise;
  }
}
